package com.jiyuren.controller;

import com.google.gson.Gson;
import com.jiyuren.spring.bean.AccessTimes;
import com.jiyuren.spring.bean.WebSite;
import com.jiyuren.spring.core.MainRun;
import com.jiyuren.spring.core.RunThread;
import com.jiyuren.spring.utils.DBConn;
import com.jiyuren.spring.utils.DatabaseSqliteUtil;
import com.jiyuren.spring.utils.RedisHelper;
import com.jiyuren.spring.utils.SpringContextUtil;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import javax.servlet.http.HttpServletRequest;

import javafx.scene.chart.PieChart;


/**
 * Created by Administrator on 2017/3/19.
 */
@Controller
@RequestMapping(value = "web/")
public class MainController {
    private Map<String, AccessTimes> globalAccTimes = new HashMap<String, AccessTimes>();
    private Gson mGson = new Gson();
    RunThread runThread = null;
    MainRun mainRun = MainRun.getInstance();
    DatabaseSqliteUtil db = SpringContextUtil.getBean("databaseUtil");
    private boolean isRunning = false;

    /**
     * 主页操作
     *
     * @return
     */
    @RequestMapping(value = "main", method = RequestMethod.GET)
    public ModelAndView main() {
        ModelAndView view = new ModelAndView("/views/main");
        db.initTable(db.getConnection());
        List<WebSite> lists = db.getList(db.getConnection());
        boolean isAllStart = true;//全部暂停
        for (WebSite list : lists) {
            if (list.getIs_run() != 1) {
                isAllStart = false;//全部开始
                break;
            }
        }
        System.out.println("isRunning = " + isRunning);
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("lists", lists);
        String jsonData = mGson.toJson(lists);
        model.put("jsonLists", jsonData);
        model.put("allStartText", isAllStart ? "全部暂停" : "全部开始");
        model.put("isRun", isRunning ? "1" : "0");
        view.addAllObjects(model);
        return view;
    }

    /**
     * 添加 更新
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "action_add/{id}", method = RequestMethod.POST)
    @ResponseBody
    public String actionAdd(@PathVariable("id") int id,
                            HttpServletRequest request) {
        String title = request.getParameter("title");
        String url = request.getParameter("url");
        String interval = request.getParameter("interval");
        String timeOut = request.getParameter("time_out");
        String accessTime = request.getParameter("access_time");
        System.out.println("id = " + id + " title = " + title);
        Connection conn = db.getConnection();
        PreparedStatement pst = null;
        int result = 0;
        if (id > 0) {//更新操作
            String sql = "update website set url = ?,title_name = ?," +
                    "access_time_interval = ?, time_out = ?,access_time = ?" +
                    " where id = ? ";
            try {
                pst = conn.prepareStatement(sql);
                pst.setString(1, url);
                pst.setString(2, title);
                pst.setString(3, interval);
                pst.setString(4, timeOut);
                pst.setString(5, accessTime);
                pst.setInt(6, id);
                result = pst.executeUpdate();
                System.out.println("result " + result);
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                DatabaseSqliteUtil.closePrepStatement(pst);
                DatabaseSqliteUtil.closeConnection(conn);
            }
        } else {//插入操作
            try {
                String sql = "insert into website (url,title_name,access_time_interval," +
                        "time_out,access_time,is_del,is_run,access_times)" +
                        "values (? ,?,?,?,?,?,?,?) ";
                pst = conn.prepareStatement(sql);
                pst.setString(1, url);
                pst.setString(2, title);
                pst.setString(3, interval);
                pst.setString(4, timeOut);
                pst.setString(5, accessTime);
                pst.setInt(6, 0);
                pst.setInt(7, 1);
                pst.setInt(8, 0);
                result = pst.executeUpdate();
                System.out.println(" result = " + result);
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                DatabaseSqliteUtil.closePrepStatement(pst);
                DatabaseSqliteUtil.closeConnection(conn);
            }
        }
        return String.valueOf(result);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "action_del/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String actionDel(@PathVariable("id") int id) {
        Connection conn = db.getConnection();
        PreparedStatement pst = null;
        int result = 0;
        try {
            String sql = "update website set is_del = 1 where id = ?";
            pst = conn.prepareStatement(sql);
            pst.setInt(1, id);
            result = pst.executeUpdate();
            System.out.println("删除 result = " + result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DatabaseSqliteUtil.closePrepStatement(pst);
            DatabaseSqliteUtil.closeConnection(conn);
        }
        return String.valueOf(result);
    }

    /**
     * 开始暂停
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "action_pause/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String actionPause(@PathVariable("id") int id) {
        Connection conn = db.getConnection();
        PreparedStatement pst = null;
        int result = 0;
        try {
            String querySql = "select is_run from website where id = ?";
            pst = conn.prepareStatement(querySql);
            pst.setInt(1, id);
            ResultSet rst = pst.executeQuery();
            if (rst.next()) {
                String sql = "update website set is_run = ? where id = ?";
                int isRun = rst.getInt("is_run");
                System.out.println("is_run = " + isRun);
                pst = conn.prepareStatement(sql);
                switch (isRun) {
                    case 0:
                        pst.setInt(1, 1);
                        break;
                    case 1:
                        pst.setInt(1, 0);
                        break;
                }
                pst.setInt(2, id);
                result = pst.executeUpdate();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DatabaseSqliteUtil.closePrepStatement(pst);
            DatabaseSqliteUtil.closeConnection(conn);
        }
        return String.valueOf(result);
    }

    /**
     * 全部开始暂停
     *
     * @return
     */
    @RequestMapping(value = "action_all_start")
    @ResponseBody
    public String actionAllStart() {
        List<WebSite> lists = db.getList(db.getConnection());
        boolean isAllStart = true;//全部暂停
        for (WebSite list : lists) {
            if (list.getIs_run() != 1) {
                isAllStart = false;//全部开始
                break;
            }
        }
        Connection conn = db.getConnection();
        PreparedStatement pst = null;
        try {
            String sql = "update website set is_run = ?";
            pst = conn.prepareStatement(sql);
            if (isAllStart) {//全部暂停
                pst.setInt(1, 0);
            } else {
                pst.setInt(1, 1);
            }
            int result = pst.executeUpdate();
            System.out.println("全部开始/全部暂停 result = " + result + " isAllStart = " + isAllStart);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DatabaseSqliteUtil.closePrepStatement(pst);
            DatabaseSqliteUtil.closeConnection(conn);
        }
        return isAllStart ? "全部暂停" : "全部开始";
    }

    /**
     * 启动
     *
     * @return
     */
    @RequestMapping(value = "action_run", method = RequestMethod.GET)
    @ResponseBody
    public String actionRun() {
        System.out.println("isRunning = " + isRunning);
        if (isRunning) {
            runThread.myStop();
            isRunning = false;
            mainRun.setStopChildListener(new MainRun.StopChildListener() {
                public boolean isStopChild() {
                    return true;
                }
            });
            runThread = null;
            System.gc();
        } else {
            runThread = new RunThread();
            mainRun.setStopChildListener(new MainRun.StopChildListener() {
                public boolean isStopChild() {
                    return false;
                }
            });
            runThread.setRunListener(new RunThread.RunListener() {
                public void onRunning() {
                    try {
                        mainRun.start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            runThread.start();
            isRunning = true;
        }
        mainRun.setGetAccessTimesListener(new MainRun.GetAccessTimesListener() {
            public void getAccessTimes(String id, String times) {
                System.out.println("id = " + id + " times = " + times);
                AccessTimes aTimes = new AccessTimes(id, times);
                globalAccTimes.put("_" + id, aTimes);
            }
        });
        return isRunning ? "1" : "0";
    }


    @RequestMapping(value = "get_access_times", method = RequestMethod.GET)
    @ResponseBody
    public String getAccessTimes() {
//        String jsonData = mRedisHelper.get(ACCESS_TIMES);
        String jsonData = mGson.toJson(globalAccTimes);
        System.out.println("jsonData = " + jsonData);
        return jsonData;
    }

}
